package com.itcast.mobileController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itcast.health.constant.MessageConstant;
import com.itcast.health.constant.RedisMessageConstant;
import com.itcast.health.pojo.Order;
import com.itcast.health.pojo.OrderInfoVo;
import com.itcast.health.pojo.Result;
import com.itcast.health.utils.JedisUtil;
import com.itcast.service.OrderMobileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

/**
 * @author Wang
 * @version v1.0
 * @date 2019/11/28 9:18
 * @description 订单
 **/
@RestController
@RequestMapping("order")
public class OrderMobileController {
    @Reference
    OrderMobileService orderMobileService;
    @Autowired
    JedisUtil jedisUtil;

    @RequestMapping("submit")
    public Result submit(@RequestBody OrderInfoVo orderInfoVo) {
        Result result=null;
        try {
            //取出订单携带的随机数
            String token = orderInfoVo.getToken();
            //从redis中删除先前存好的token,如果能删除,就说明为第一次提交
            Long del = jedisUtil.del(token);
            if (del==0){
                return Result.error("请求无效");
            }

            //从redis中取出验证码与用户输入的验证码比较
            String redisCode = jedisUtil.get(orderInfoVo.getTelephone() + RedisMessageConstant.SENDTYPE_ORDER);
            if (redisCode == null || !(redisCode.equals(orderInfoVo.getValidateCode()))) {
                return Result.error(MessageConstant.VALIDATECODE_ERROR);
            }
            //设置预约类型(调用此接口默认为微信预约)
            orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);
            //创建订单,返回预约成功后的信息
             result = orderMobileService.createOrder(orderInfoVo);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
    }

    /**
     * 预约成功页面所需的回显数据
     */
    @RequestMapping("findById")
    public Result findById(Integer id) {
        try {
          Map map = orderMobileService.findById(id);
            return Result.success("",map);
        } catch (Exception e) {
            e.printStackTrace();
            return  Result.error("");
        }
    }
       /**
        * 防止表单重复提交
        * */
       @RequestMapping("getToken")
       public Result getToken(){
           //生成随机数
           String token = UUID.randomUUID().toString();
           //将随机数存入redis中
         // jedisUtil.setex(token,60*60,token);
           //返回随机数让提交订单时携带
           return Result.success("",token);
       }

}